package com.mgs.tagger.controller
{
	import com.mgs.tagger.appdata.dto.TagDTO;
	import com.mgs.tagger.fsdata.FsDataUtil;
	import com.mgs.tagger.log.Level;
	import com.mgs.tagger.log.Logger;
	import com.mgs.tagger.model.FileItemUI;
	
	import flash.desktop.ClipboardFormats;
	import flash.filesystem.File;
	
	import mx.core.DragSource;
	import mx.core.IUIComponent;
	import mx.events.DragEvent;
	import mx.managers.DragManager;

	public class FileItemController
	{
		public function FileItemController()
		{
		}
		
		public static function transformFileAsDirectory(fileItem:FileItemUI):void{
			var name:String = fileItem.file.name;
			var p:int = name.lastIndexOf(".");
			if(p < 0){
				Logger.instance.log(Level.SEVERE, "file " + fileItem.file.nativePath + " have no extension");
			}
			name = name.substring(0, p);
			var dir:File = fileItem.file.parent.resolvePath(name);
			dir.createDirectory();
			// move file
			fileItem.file.moveTo(dir.resolvePath(fileItem.file.name));
			// update object.
			fileItem.dto.filename = dir.name;
			fileItem.file = dir;
			fileItem.name = dir.name;
		}
		
		public static function handleDropComplete(fileItem:FileItemUI, event:DragEvent):void{
			if(event.dragSource.hasFormat("TagDTO")){
				var tag:TagDTO = event.dragSource.dataForFormat("TagDTO") as TagDTO;
				TagController.instance.tag(fileItem, tag);
			}else if(event.dragSource.hasFormat(ClipboardFormats.FILE_LIST_FORMAT)){
				var files:Array = event.dragSource.dataForFormat(ClipboardFormats.FILE_LIST_FORMAT) as Array;
				var oneFile:File = files[0] as File;
				if(!fileItem.file.isDirectory){
					transformFileAsDirectory(fileItem);
				}
				var dst:File = fileItem.file.resolvePath(oneFile.name);
				Logger.instance.log(Level.INFO, "move " + oneFile.nativePath + " to " + dst.nativePath);
				oneFile.moveTo(dst, false);
				fileItem.icon = FsDataUtil.loadDataFromFile(dst);
			}
		
		}
		public static function handleDropAccept(event:DragEvent):void{
			if(event.dragSource.hasFormat("TagDTO") ||
				event.dragSource.hasFormat(ClipboardFormats.FILE_LIST_FORMAT)){
				DragManager.acceptDragDrop(event.currentTarget as IUIComponent);
			}
		}
	}
}